<style>
a {
  text-decoration: none;
}

a:link {
  color: darkblue;
}

a:visited {
  color: darkblue;
}

a:hover {
  color: purple;
}

a:active {
  color: red;
}
</style>
<template>
  <div style="background-color: cornflowerblue;overflow: hidden;height: 100vh;position:relative;">
    <div style="width: 600px; margin: 100px auto; padding: 20px 50px 100px 50px; background: #fff;">
      <a href="javascript:void(0)" @click="$router.push('/frontState/homePage')">
        <i style="font-size: 25px" class="bi-box-arrow-left"/>
        <span style="vertical-align: top;line-height: 33px;margin-left: 5px">退出后台系统</span>
      </a>
      <h1 style="margin: 10px auto; text-align: center;">管理员登录</h1>
      <el-form :model="loginData" :rules="loginRule" ref="ruleForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginData.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input show-password v-model="loginData.password"/>
        </el-form-item>
        <el-form-item style="position: absolute;left: 50%;transform: translateX(-71%)">
          <el-button type="primary" @click="loginSubmit">登录</el-button>
          <el-button type="danger" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "login",
  data() {
    return {
      loginData: {
        username: "",//用户名
        password: "",//密码
        ip: "",//登录时所在位置的ip
        userAgent: ""//登录时所使用的设备
      },
      loginRule: {
        username: [
          {required: true, message: "用户名为空", trigger: "blur"},
          {pattern: /^[a-zA-Z]{1}[0-9a-zA-Z]{3,15}$/, message: "用户名第一位必须为字母，长度在4~15之间", trigger: "blur"},
        ],
        password: [
          {required: true, message: "密码为空", trigger: "blur"},
          {pattern: /^[\u0020-\u007e]{4,16}$/, message: "密码的长度必须是4~16位", trigger: "blur"}
        ]
      },
      loginLogData: {
        adminId: "",
        nickname: "",
        ip: "",//
        device: "",//
        city: "",//
        Longitude: "",//
        Latitude: "",//
      }
    };
  },
  methods: {
    //提交表单信息
    loginSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.getAdminLocation();
          this.loginData.userAgent = navigator.userAgent;
          this.loginLogData.device = navigator.userAgent.match(/[^\(\)]+(?=\))/g)[0].split(" ")[0];
          let url = "http://localhost:9999/zx-sso/admin/sso/login"
          let loginData = this.qs.stringify(this.loginData);
          this.axios.post(url, loginData).then((response) => {
            let result = response.data;
            if (result.state === 200) {
              result = result.data;
              localStorage.setItem("adminJwt", result.tokenHeader + result.tokenValue);
              this.getAdminData(this.loginData.username);
            } else {
              this.$message({message: result.message, type: "error"})
            }
          })
        }
      })
    },
    //获取当前定位信息
    getAdminLocation() {
      let key = "JHNBZ-UF2H7-7U4XG-H7WQM-HNHWK-RTFXM"
      let secretKey = "SUHjLSz5PB1VahzkG376Kkhbhr2ajWWt"
      let sig = this.md5("/ws/location/v1/ip?callback=jsonpCallback&key=" + key + "&output=jsonp" + secretKey);
      this.$jsonp("https://apis.map.qq.com/ws/location/v1/ip",
          {callbackQuery: 'callback', callbackName: 'jsonpCallback', key: key, output: 'jsonp', sig: sig}
      ).then((response) => {
        if (response.message === "Success") {
          let result = response.result;
          this.loginData.ip = result.ip;
          this.loginLogData.ip = result.ip;
          this.loginLogData.city = result.ad_info.nation + "，" + result.ad_info.province + result.ad_info.city + result.ad_info.district;
          this.loginLogData.Longitude = result.location.lng;
          this.loginLogData.Latitude = result.location.lat;
        } else {
          this.$message({message: "未能成功获取ip地址", type: "warning"})
        }
      })
    },
    //获取管理员相关信息
    getAdminData(username) {
      let url = "http://localhost:9999/zx-ams/admin/adminData?username=" + username;
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        let result = response.data;
        if (result.state === 200) {
          result = result.data;
          this.loginLogData.adminId = result.id;
          this.loginLogData.nickname = result.nickname;
          localStorage.setItem("adminId", result.id);
          localStorage.setItem("adminName", result.username)
          localStorage.setItem("adminNickname", result.nickname)
          localStorage.setItem("adminIcon", result.icon);
          this.$router.push('/backState/adminHome');
          this.setLoginLog();
        }
      })
    },
    setLoginLog() {
      let url = "http://localhost:9999/zx-ams/LoginLog/record"
      let data = this.qs.stringify(this.loginLogData);
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, data).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state !== 200) {
          this.$message({message: "登录日志上传不成功", type: "warning"})
        }
      })
    },
    //重置表单信息
    resetForm() {
      this.$refs.ruleForm.resetFields();
    }
  },
  mounted() {
  }
}
</script>

